﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FlightSearchServer
{
    public class VendorsDB
    {
        private static VendorsDB _instance = null;

        private static Object locker = new Object();

        private IList<TicketsVendors> vendors = new List<TicketsVendors>( );

        public enum Status
        {
            VENDOR_ALREADY_REGISTERED,
            VENDOR_NAME_ALREADY_REGISTERED,
            VENDOR_LOCATION_ALREADY_REGISTERED,
            REGISTRATION_SUCCESS,
            REGISTRATION_FAILED
        }

        private VendorsDB()
        {

        }

        public static VendorsDB getInstance()
        {
            if (_instance == null)
            {
                lock (locker)
                {
                    if (_instance == null)
                    {
                        _instance = new VendorsDB();
                    }
                }
            }
            return _instance;
        }

        public Status addVendor( TicketsVendors vendor)
        {
            Status status = Status.REGISTRATION_SUCCESS;
            lock (vendors)
            {
                foreach (TicketsVendors tVendor in vendors )
                {
                    if ( vendor.name.Equals( tVendor.name)) {
                        Console.WriteLine( "Vendor with same name({0}) has been already registered.", vendor.name);
                        return Status.VENDOR_NAME_ALREADY_REGISTERED;
                    }
                    if (vendor.location.Equals(tVendor.location))
                    {
                        Console.WriteLine("Vendor with same location({0}) has been already registered.", vendor.location);
                        return Status.VENDOR_LOCATION_ALREADY_REGISTERED;
                    }
                }
                vendors.Add(vendor);
            }
            return status;
        }

        public IList<TicketsVendors> getVendors( )
        {
            IList<TicketsVendors> result;
            lock (vendors)
            {
                result = vendors;
            }
            return result;
        }

        public TicketsVendors find(string vendorName)
        {
            TicketsVendors vendor = null;
            lock (vendors)
            {
                foreach (TicketsVendors tmp in vendors)
                {
                    if (tmp.name.Equals(vendorName))
                    {
                        vendor = tmp;
                        break;
                    }
                }
            }
            return vendor;
        }
    }
}